using System.Collections.Generic;
using UnityEngine;

namespace Scanline.GUI
{
    public class Board : MonoBehaviour
    {
        #region 像素
        private Dictionary<Vector2Int, Pixel> pixels = new();

        public void SetInternelPixels(List<Vector2Int> positions)
        {
            foreach (Pixel pixel in pixels.Values)
            {
                pixel.IsInternal = false;
            }
            for (int i = 0; i < positions.Count; i++)
            {
                pixels[positions[i]].IsInternal = true;
            }
        }

        private void GenetatePixels()
        {
            for (int i = range.xMin; i <= range.xMax; i++)
            {
                for (int j = range.yMin; j <= range.yMax; j++)
                {
                    Vector2Int board = new(i, j);
                    Pixel pixel = Instantiate(prefab_pixel, BoardToWorld(board), Quaternion.identity, transform).GetComponent<Pixel>();
                    pixels.Add(board, pixel);
                }
            }
        }

        #endregion

        #region 变换
        [SerializeField]
        private RectInt range;

        public Vector2Int WorldToBoard(Vector3 world)
        {
            Vector3 relative = world - transform.position;
            return new Vector2Int(Mathf.RoundToInt(relative.x), Mathf.RoundToInt(relative.y));
        }

        public Vector3 BoardToWorld(Vector2Int board)
        {
            Vector3 relative = new(board.x, board.y);
            return relative + transform.position;
        }

        private void OnDrawGizmos()
        {
            Gizmos.color = Color.green;
            Vector3 worldMin = BoardToWorld(range.min);
            Vector3 worldMax = BoardToWorld(range.max);
            Gizmos.DrawWireCube((worldMin + worldMax) / 2, worldMax - worldMin + Vector3.one);
        }
        #endregion

        public static Board FindInstance() => GameObject.Find(nameof(Board)).GetComponent<Board>();

        [SerializeField]
        private GameObject prefab_pixel;

        private void Awake()
        {
            GenetatePixels();
        }
    }
}